package com.bicon.botu.mall.base.service.impl;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.bicon.botu.mall.base.common.BaseConstants;
import com.bicon.botu.mall.base.common.ValidationUtil;
import com.bicon.botu.mall.base.dto.DeliveryPointDto;
import com.bicon.botu.mall.base.entity.DeliveryPoint;
import com.bicon.botu.mall.base.mapper.DeliveryPointMapper;
import com.bicon.botu.mall.base.service.IDeliveryPointService;
import com.bicon.botu.core.base.common.Constants;
import com.bicon.botu.core.base.common.entity.BaseResult;
import com.bicon.botu.core.base.common.utils.IdGen;
import com.bicon.botu.core.base.common.utils.JsonUtil;
import com.bicon.botu.core.base.repository.redis.RedisHandler;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 发货点 服务实现类
 *
 * @author liushujie
 * @date 2017/7/19 下午 14:49
 */
@Service
public class DeliveryPointServiceImpl extends ServiceImpl<DeliveryPointMapper, DeliveryPoint> implements IDeliveryPointService {

    @Autowired
    RedisHandler redisHandler;

    /**
     * 发货点redisKey
     */
    private static final String REDIS_KEY = BaseConstants.BOTU_MALL_DELIVERYPOINT_CONFIG;
    /**
     * 根据商户ID添加收货点
     * @param tenantId
     * @param name
     * @param shipper
     * @param region
     * @param address
     * @param telephone
     * @return boolean
     */
    @Override
    public BaseResult insert(String tenantId, String name, String shipper, String region, String address, String telephone) {

        //根据商户ID,和发货点名称检查是否有相同的发货点已存在，存在则返回提示信息。反之创建，并初始化缓存。
        DeliveryPoint deliveryPoint = new DeliveryPoint().selectOne(new EntityWrapper<DeliveryPoint>().eq("tenant_id", tenantId).eq("name", name)
                .eq("logic_delete", Constants.DEL_LOGIC_NORMAL));
        if (deliveryPoint != null) {
            return new BaseResult(Constants.RESPONSE_CODE_601, Constants.RESPONSE_MESSAGE_601);
        }

        //新增发货点
        DeliveryPoint deliveryPoint1 = new DeliveryPoint();
        deliveryPoint1.preInsert();
        deliveryPoint1.setTenantId(tenantId);
        deliveryPoint1.setOrderNumber(IdGen.uuid());
        deliveryPoint1.setName(name);
        deliveryPoint1.setShipper(shipper);
        deliveryPoint1.setRegion(region);
        deliveryPoint1.setAddress(address);
        deliveryPoint1.setTelephone(telephone);
        deliveryPoint1.setIsDelivery(0);
        deliveryPoint1.setIsReceive(0);
        boolean result = deliveryPoint1.insert();
        if (!result) {
            return new BaseResult(Constants.RESPONSE_CODE_500, Constants.RESPONSE_MESSAGE_500);
        }
        //缓存初始化 公共initDeliveryPointRedis
        return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200);
    }

    /**
     * 初始化所有商户的发货点到redis
     * @return
     */
    @Override
    public BaseResult initDeliveryPointToRedis() {
        //1、清除缓存
        redisHandler.getLocalRedisTemplate().remove(REDIS_KEY, "");
        //2、查询出所有的正常状态的所有商户下的送货点配置列表
        List<DeliveryPoint> deliveryPointList = new DeliveryPoint().selectList(new EntityWrapper<DeliveryPoint>()
                .eq("logic_delete", Constants.DEL_LOGIC_NORMAL).eq("logic_delete", Constants.DEL_LOGIC_NORMAL).orderBy("is_delivery",false).orderBy("is_receive",false).orderBy("create_date", false));
        List<String> stringList = new ArrayList<>();
        for (DeliveryPoint deliveryPoint : deliveryPointList) {
            stringList.add(JsonUtil.toJson(deliveryPoint));
        }
        //保存到redis上
        redisHandler.getLocalRedisTemplate().cacheList(REDIS_KEY, "", stringList);
        return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200);
    }

    /**
     * 删除发货点
     * @param id 发货点ID
     * @return true false
     */
    @Override
    public BaseResult deleteDeliveryPoint(String id) {
        String[] idArray = id.split(",");
        List<DeliveryPoint> deliveryPointList = new ArrayList<>();
        for (int i = 0; i < idArray.length; i++) {
            DeliveryPoint deliveryPoint = new DeliveryPoint();
            deliveryPoint.setId(idArray[i]);
            deliveryPoint.setLogicDelete(Constants.DEL_LOGIC_DELETE);
            deliveryPoint.preUpdate();
            deliveryPointList.add(deliveryPoint);
        }
        boolean result = this.updateBatchById(deliveryPointList);
        if (!result) {
            return new BaseResult(Constants.RESPONSE_CODE_500, Constants.RESPONSE_MESSAGE_500);
        }
        return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200);
    }

    /**
     * 设置为默认发货点
     * @param id 发货点ID
     * @return
     */
    @Override
    public BaseResult setDealutDelivery(String id,Integer state) {
        //检查是否已经有默认发货点
        DeliveryPoint deliveryPoint = new DeliveryPoint().selectOne(new EntityWrapper<>().eq("is_delivery", 1)
                .eq("logic_delete", Constants.DEL_LOGIC_NORMAL));
        //否则设置发货点
        if(!ValidationUtil.isEmpty(deliveryPoint)){
            //存在默认发货，修改为不是默认发货
            deliveryPoint.setIsDelivery(0);
            deliveryPoint.updateById();
        }
        //更新操作，设置为默认发货点
        DeliveryPoint deliveryPoint1 = new DeliveryPoint();
        deliveryPoint1.preUpdate();
        deliveryPoint1.setId(id);
        deliveryPoint1.setIsDelivery(state);
        boolean result = deliveryPoint1.updateById();
        if (!result) {
            return new BaseResult(Constants.RESPONSE_CODE_500, Constants.RESPONSE_MESSAGE_500);
        }
        return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200);
    }

    /**
     * 设置为默认收货点
     * @param id 收货点ID
     * @return
     */
    @Override
    public BaseResult setDealutReceive(String id,Integer state) {
        //检查是否已经有默认发货点
        DeliveryPoint deliveryPoint = new DeliveryPoint().selectOne(new EntityWrapper<>().eq("is_receive", 1)
                .eq("logic_delete", Constants.DEL_LOGIC_NORMAL));
        if(!ValidationUtil.isEmpty(deliveryPoint)){
            deliveryPoint.setIsReceive(0);
            deliveryPoint.updateById();
        }
        //更新操作，设置为默认收货点
        DeliveryPoint deliveryPoint1 = new DeliveryPoint();
        deliveryPoint1.preUpdate();
        deliveryPoint1.setId(id);
        deliveryPoint1.setIsReceive(state);
        boolean result = deliveryPoint1.updateById();
        if (!result) {
            return new BaseResult(Constants.RESPONSE_CODE_500, Constants.RESPONSE_MESSAGE_500);
        }
        return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200);
    }

    /**
     * 修改发货点
     * @param id 发货点ID
     * @param tenantId 商户ID
     * @param name 收货点名称
     * @param shipper 收货人
     * @param region 区域
     * @param address 详细地址
     * @param telephone 联系方式
     * @return boolean true、false
     */
    @Override
    public BaseResult updateDeliveryPoint(String id, String tenantId, String name, String shipper, String region, String address, String telephone) {
        //校验是否存在
        DeliveryPoint deliveryPoint1 = new DeliveryPoint().selectOne(new EntityWrapper<DeliveryPoint>().notIn("id",id).eq("tenant_id", tenantId).eq("name", name)
                .eq("logic_delete", Constants.DEL_LOGIC_NORMAL));
        if (deliveryPoint1 != null) {
            return new BaseResult(Constants.RESPONSE_CODE_601, Constants.RESPONSE_MESSAGE_601);
        }
        DeliveryPoint deliveryPoint = new DeliveryPoint().selectOne(new EntityWrapper<>().eq("id", id)
                .eq("logic_delete", Constants.DEL_LOGIC_NORMAL));
        if (ValidationUtil.isEmpty(deliveryPoint)) {
            return new BaseResult(Constants.RESPONSE_CODE_404, Constants.RESPONSE_MESSAGE_404);
        }
        deliveryPoint.preUpdate();
        //参数校验
        if (!ValidationUtil.isEmpty(name)) {
            deliveryPoint.setName(name);
        }
        if (!ValidationUtil.isEmpty(shipper)) {
            deliveryPoint.setShipper(shipper);
        }
        if (!ValidationUtil.isEmpty(region)) {
            deliveryPoint.setRegion(region);
        }
        if (!ValidationUtil.isEmpty(address)) {
            deliveryPoint.setAddress(address);
        }
        if (!ValidationUtil.isEmpty(telephone)) {
            deliveryPoint.setTelephone(telephone);
        }
        boolean result = deliveryPoint.updateById();
        if (!result) {
            return new BaseResult(Constants.RESPONSE_CODE_500, Constants.RESPONSE_MESSAGE_500);
        }
        return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200);
    }


    /**
     * 根据发货点ID获取发货点详情
     * @param id 发货点ID
     * @return 发货点对象
     */
    @Override
    public DeliveryPointDto details(String id) {
        DeliveryPoint deliveryPoint = new DeliveryPoint().selectOne(new EntityWrapper<>().eq("id", id)
                .eq("logic_delete", Constants.DEL_LOGIC_NORMAL));
        DeliveryPointDto deliveryPointDto = new DeliveryPointDto();
        if (!ValidationUtil.isEmpty(deliveryPoint)) {
            BeanUtils.copyProperties(deliveryPoint,deliveryPointDto);
        }
        return deliveryPointDto;

    }
}
